package org.jeecg.modules.fund.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.fund.entity.FundSearchHistory;
import org.jeecg.modules.fund.service.IFundSearchHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "日期管理")
@RequestMapping("/sys/fund/search/history")
@Slf4j
public class FundSearchHistoryController {
    @Autowired
    private IFundSearchHistoryService fundSearchHistoryService;

    /**
     * 保存搜索历史
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Result<String> add(@RequestBody FundSearchHistory history) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        history.setUserId(sysUser.getId());
        fundSearchHistoryService.create(history);
        return Result.ok("创建成功");
    }

    /**
     * 清空历史
     * @return
     */
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public Result<String> clear() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        fundSearchHistoryService.remove(new LambdaQueryWrapper<FundSearchHistory>().eq(FundSearchHistory::getUserId,sysUser.getId()));
        return Result.ok("清空成功");
    }

    /**
     * 搜索历史
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<List<FundSearchHistory>> list() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<FundSearchHistory> dataList = fundSearchHistoryService.list(new LambdaQueryWrapper<FundSearchHistory>()
                .eq(FundSearchHistory::getUserId,sysUser.getId())
                .orderByDesc(FundSearchHistory::getCreateTime));
        return Result.ok(dataList);
    }

    /**
     * 热搜
     * @return
     */
    @RequestMapping(value = "/hotSearch", method = RequestMethod.GET)
    public Result<List<FundSearchHistory>> hotSearch() {
        List<FundSearchHistory> dataList = fundSearchHistoryService.list(new QueryWrapper<FundSearchHistory>()
                .select("fund_id,name,count(*) as 'total'")
                .groupBy("fund_id,name")
                .orderByDesc("count(*)").last("limit 20"));
        return Result.ok(dataList);
    }
}
